package com.lhdx.practical.service.impl;

import com.lhdx.practical.bean.Content;
import com.lhdx.practical.dao.ContentDao;
import com.lhdx.practical.service.ContentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Service("ContentService")
public class ContentServiceImpl implements ContentService {
    @Autowired
    private ContentDao contentDao;

    @Override
    public void save(Content content) {
        contentDao.save(content);
    }

    @Override
    public void deleteById(long id) {
        contentDao.deleteById(id);
    }

    @Override
    public Content findOne(long id) {
        return contentDao.findById(id);
    }

    @Override
    public List<Content> findAllBySid(long sid) {
        return contentDao.findAllBySid(sid);
    }

    @Override
    public List<Content> findAllBySidAndMidAndGradeid(long sid,long mid,long gradeid) {
        return contentDao.findAllBySidAndMidAndGradeid(sid,mid,gradeid);
    }

    @Override
    public Content findByGradeidAndSid(long gradeid, long sid) {
        return contentDao.findByGradeidAndSid(gradeid,sid);
    }

    @Override
    public Page<Content> getResultList(long mid,long sid,long gradeid, int orderby,int page, int pagesize) {
        Sort sort = null;
        if(orderby == 0){
            sort = new Sort(Sort.Direction.DESC, "createtime");
        }else{
            sort = new Sort(Sort.Direction.ASC, "sort");
        }
        Pageable pageable = PageRequest.of(page == 0 ? 0 : page -1, pagesize, sort);
        Page<Content> data = contentDao.findAll(new Specification<Content>(){
            @Override
            public Predicate toPredicate(Root<Content> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> list = new ArrayList<Predicate>();
                list.add(cb.equal(root.get("mid"),mid));
                list.add(cb.equal(root.get("sid"),sid));
                list.add(cb.equal(root.get("gradeid"),gradeid));
                Predicate[] p = new Predicate[list.size()];
                return cb.and(list.toArray(p));
            }
        },pageable);
        return data;
    }

    @Override
    public void updateClicks(long id, int clicks) {
        contentDao.updateClicks(id,clicks);
    }

    @Override
    public void updateDownloads(long id, int downloadcount) {
        contentDao.updateDownloads(id,downloadcount);
    }
}
